<?php

class Users extends Controller {
                  
	function Users()
	{
		parent::Controller();	

        if(!admin_session_check()) redirect('admin/login');

        $this->load->model('adminusermodel');          
	}     
    
    function index()
    {
        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        $data["list"] = $this->adminusermodel->get_all_users();
        $data["roles"] = $this->adminusermodel->get_all_roles();  
        
        $data["response"] = get_response();        

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header', array('selected'=>'users'));  
        $this->load->view("admin/default/nav_users", array('selected' => 'users'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/users/users_list', $data);   
        $this->load->view('admin/default/footer');   

    }  
   
    function edit($id = NULL)
    {
        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        if($id == NULL) show_404();
        $data["item"] = $this->adminusermodel->get_user($id); 
        if(empty($data["item"])) show_404();

        $this->_process_form();

        $data["roles"] = $this->adminusermodel->get_all_roles(); 
        
        $data["token"] = generate_token("users",720);  
        $data["action"] = "update";        

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header', array('selected'=>'users'));  
        $this->load->view("admin/default/nav_users", array('selected' => 'users'));
        $this->load->view('admin/users/users_form', $data);   
        $this->load->view('admin/default/footer');   

    } 

    function edit_profile()
    {

        $id = $this->session->userdata("admin_id");
        $data["item"] = $this->adminusermodel->get_user($id); 
        if(empty($data["item"])) show_404();

        $this->_process_form();
        
        $data["token"] = generate_token("users",720);  
        $data["action"] = "edit_profile";        

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header');  
        $this->load->view('admin/users/userprofile_form', $data);   
        $this->load->view('admin/default/footer');   

    }    
     
    function create()
    {               
        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        $this->_process_form();

        $data["item"] = $this->adminusermodel->get_user();
        $data["roles"] = $this->adminusermodel->get_all_roles();

        $data["token"] = generate_token("users",720);  
        $data["action"] = "create";        

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header', array('selected'=>'users'));  
        $this->load->view("admin/default/nav_users", array('selected' => 'users'));
        $this->load->view('admin/users/users_form', $data);   
        $this->load->view('admin/default/footer');   

    }    

    private function _process_form()
    {

        $this->load->library("form_validation");       

        if($this->input->post("submit_action") !== FALSE){

            if ($this->_validate_form()){

                if (validate_token("users",$this->input->post("token",TRUE))){

                    $data = array(
                        'Username' => $this->input->post("username"),
                        'Role' => $this->input->post("role")
                    );

                    if ($this->input->post("password",TRUE) !== "")
                        $data['Password'] = md5($this->input->post("password"));

                    switch($this->input->post("submit_action")){    

                        case 'create':
                                                           
                            $new_id = $this->adminusermodel->create_user($data);
                            set_response('success','User <i>'.$data['Username'].'</i> was created');
                            redirect('admin/users');

                        break;
                        case 'update':

                            $id = $this->input->post("id");
                            if ($id==ADMIN_MASTER_ID) unset($data['Role']);
                            $this->adminusermodel->update_user($id, $data);
                            set_response('success','User <i>'.$data['Username'].'</i> was updated');
                            redirect('admin/users');

                        break;
                        case 'edit_profile':

                            $id = $this->session->userdata("admin_id");

                            unset($data['Role']);
                            $this->adminusermodel->update_user($id, $data);
                            $valid_user = $this->adminusermodel->get_user($id);
                            admin_session_create($valid_user);

                            set_response('success','Your user profile was updated. Please remember to use the new information next time you log in');
                            redirect('admin');

                        break;        

                    }   

                }

            }

        }                         

    }

    private function _validate_form(){
        
        $config = array(
                        array(
                         'field'   => 'username',
                         'label'   => 'Username',
                         'rules'   => 'trim|required|xss_clean|min_length[4]|max_length[36]|callback_check_duplicated'
                        ),
                        array(
                         'field'   => 'role',
                         'label'   => 'User type',
                         'rules'   => 'trim|required|xss_clean|max_length[36]'
                        )
                    );

        switch($this->input->post("submit_action")){    

            case 'create':

                $config[] = array(
                         'field'   => 'password',
                         'label'   => 'Password',
                         'rules'   => 'trim|required|xss_clean|min_length[4]|max_length[36]'
                        );

            break;
            case 'update':

                if ($this->input->post("password") !== ""){
                    $config[] = array(
                             'field'   => 'password',
                             'label'   => 'New Password',
                             'rules'   => 'trim|required|xss_clean|min_length[4]|max_length[36]'
                            );
                }

            break;        

        }   
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }


     public function check_duplicated($name){ 

        $id = $this->input->post("id");

        if($this->adminusermodel->is_duplicated('Username',$name,$id)){
            $this->form_validation->set_message('check_duplicated', "That username already exists");
            return FALSE;
        }else{
            return TRUE;    
        }
    } 


    function deactivate($id = false){

        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        if($id == NULL) show_404();  
        $data = array('Active' => 0);

        if($id==ADMIN_MASTER_ID) set_response('error', "You can't deactivate the Master Administrator");
        else{
            $this->adminusermodel->update_user($id, $data);
            $item = $this->adminusermodel->get_user($id);
            set_response('success', "User <i>".$item["Username"]."</i> is now inactive");
        }
        redirect('admin/users');
    }
    function activate($id = false){

        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        if($id == NULL) show_404();  
        $data = array('Active' => 1);
        $this->adminusermodel->update_user($id, $data);  
        $item = $this->adminusermodel->get_user($id);
        set_response('success', "User <i>".$item["Username"]."</i> is now active");
        redirect('admin/users');
    }

    function remove($id = false){

        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        if($id == NULL) show_404(); 
        $data["item"] = $this->adminusermodel->get_user($id); 

        if($id==ADMIN_MASTER_ID){ 
            set_response('error', "You can't delete the Master Administrator");
        } else if(empty($data["item"])){
            set_response('error', "The supplier you're attempting to delete does not exist");
        } else {
            $item = $this->adminusermodel->get_user($id);
            $r = "You're about to permanently delete user <i>".$item['Username']."</i>";
            $r .= '<div class="buttons_block">';
            $r .= '<a class="button" href="'.site_url('admin/users/confirm_removal/'.$item["id"]).'">CONFIRM DELETION</a> ';
            $r .= '<a class="button" href="'.site_url('admin/users').'">CANCEL</a>';
            $r .= '</div>';
            set_response('warning', $r);
        }     
        redirect('admin/users');
         
    }
    function confirm_removal($id = false){

        $allowed_roles = array(ROLE_ADMIN);
        if(!is_allowed($allowed_roles)) show_404();

        if($id == NULL) show_404();  
        $data["item"] = $this->adminusermodel->get_user($id);

        if($id==ADMIN_MASTER_ID){
            set_response('error', "You can't delete the Master Administrator");
        } else if(empty($data["item"])){
            set_response('error', "The supplier you're attempting to delete does not exist");
        } else{
            $this->adminusermodel->delete_user($id);
            set_response('success', "The supplier <i>".$item["Username"]."</i> was deleted.");
        }
        redirect('admin/users'); 
    }

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */